import { TypeOf } from './index';

interface StorageParams {
  key: string;
  value?: any;
  islocal?: boolean;
}

/**
 * 获取sessionStorage数据
 * @param {StorageParams} params 参数对象
 * @returns {any}
 */
export const getStorage = ({ key, islocal = false }: StorageParams): any => {
  let storage: string;
  if (islocal) {
    storage = localStorage.getItem(key) || '';
    const isbool: boolean = storage.includes('{') && storage.includes('}');
    return storage !== '' ? (isbool ? JSON.parse(storage) : storage) : false;
  } else {
    storage = sessionStorage.getItem(key) || '';
    const isbool: boolean = storage.includes('{') && storage.includes('}');
    return storage !== '' ? (isbool ? JSON.parse(storage) : storage) : false;
  }
};

/**
 * 保存数据到sessionStorage
 * @param {StorageParams} params 参数对象
 * @returns {void}
 */
export const setStorage = ({ key, value, islocal = false }: StorageParams): void => {
  const obj: string[] = ['object', 'function', 'array', 'date', 'formData'];
  const resq: string = obj.includes(TypeOf(value)) ? JSON.stringify(value) : value;
  if (islocal) {
    localStorage.setItem(key, resq);
  } else {
    sessionStorage.setItem(key, resq);
  }
};

/**
 * 删除数据
 * @param {StorageParams} params 参数对象
 * @returns {void}
 */
export const removeStore = ({ key, islocal = false }: StorageParams): void => {
  if (islocal) {
    localStorage.removeItem(key);
  } else {
    sessionStorage.removeItem(key);
  }
};
